<template>
  <BasicTable
    ref="tableRef"
    :initial-params="initialParams"
    :query-api="fetchList"
    :create-api="createTask"
    :update-api="updateTask"
    :delete-api="deleteTask"
    :query-fields="queryFields"
    :table-fields="tableFields"
    :form-fields="formFields"
    :form-rules="formRules"
    @reset-query="handleResetQuery"
    @open-form="handleOpenForm"
    @close-form="handleCloseForm"
  ></BasicTable>
</template>

<script setup lang="tsx">
import { ElMessage, ElMessageBox } from "element-plus";
import { flatten } from "lodash";
import { Fragment, ref } from "vue";
import { cabinet } from "../../api/cabinet";
import { deviceProfile } from "../../api/deviceProfile";
import {
  activeTask,
  controlTask,
  createTask,
  deleteTask,
  fetchList,
  fetchMapList,
  updateTask,
} from "../../api/task";
import BasicTable from "../../components/BasicTable";
import parseTime from "../../utils/parseTime";

const initialParams = {
  limit: 99999,
};

const TaskType = {
  0: "全部巡检",
  1: "自动任务",
  2: "手动任务",
};

const time = ref([]);

const queryFields = [
  {
    prop: "name",
    title: "名称",
  },
  {
    slot: (params) => (
      <el-date-picker
        v-model={time.value}
        type="datetimerange"
        value-format="YYYY-MM-DD HH:mm:ss"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        onChange={(value) => handleQueryDateTimeChange(value, params)}
      />
    ),
  },
  {
    slot: (params) => (
      <el-select class="w-full" v-model={params.value.type} placeholder="类型">
        {Object.keys(TaskType).map((key) => (
          <el-option label={TaskType[key]} value={key}></el-option>
        ))}
      </el-select>
    ),
  },
  {
    slot: (params) => (
      <el-select
        class="w-full"
        v-model={params.value.activeStatus}
        placeholder="激活状态"
      >
        <el-option label="激活" value={1}></el-option>
        <el-option label="未激活" value={0}></el-option>
      </el-select>
    ),
  },
];

const tableFields = [
  {
    prop: "name",
    title: "名称",
  },
  {
    prop: "startTime",
    title: "开始时间",
    formatter: (row) => {
      return parseTime(row);
    },
  },
  {
    prop: "endTime",
    title: "结束时间",
    formatter: (row) => {
      return parseTime(row);
    },
  },
  {
    prop: "type",
    title: "类型",
    slot: (row) => {
      return TaskType[row.type];
    },
  },
  {
    prop: "activeStatus",
    title: "状态",
    slot: (row) => (
      <span class={row.activeStatus ? "text-green-500" : "text-red-500"}>
        {row.activeStatus ? "已激活" : "未激活"}
      </span>
    ),
  },
  {
    title: "操作",
    action: true,
    slot: (row) => (
      <Fragment>
        <el-button link type="success" onClick={() => handleCopy(row)}>
          复制
        </el-button>
        <el-button
          v-show={!row.activeStatus}
          link
          type="warning"
          onClick={async () => {
            await ElMessageBox.confirm("确认继续操作吗", "警告");
            await handleActive(row);
            ElMessage({ type: "success", message: "激活成功" });
          }}
        >
          激活
        </el-button>
        <el-button link type="info" onClick={() => handleControl(row, "start")}>
          开始
        </el-button>
        <el-button link type="info" onClick={() => handleControl(row, "pause")}>
          暂停
        </el-button>
        <el-button
          link
          type="info"
          onClick={() => handleControl(row, "continues")}
        >
          继续
        </el-button>
        <el-button
          link
          type="info"
          onClick={() => handleControl(row, "cancel")}
        >
          取消
        </el-button>
      </Fragment>
    ),
  },
];

const formRules = {
  name: [{ required: true, message: "请输入名称" }],
  type: [{ required: true, message: "请选择类型" }],
  mid: [{ required: true, message: "请选择地图" }],
  startTime: [{ required: true, message: "请选择开始时间" }],
  endTime: [{ required: true, message: "请选择结束时间" }],
  cabinetIds: [{ required: true, message: "请选择巡检机柜" }],
};

const formFields = [
  {
    prop: "name",
    title: "名称",
  },
  {
    prop: "startTime",
    title: "开始时间",
    slot: (form) => (
      <el-date-picker
        v-model={form.value.startTime}
        value-format="YYYY-MM-DDTHH:mm:ss"
        type="datetime"
        placeholder="开始时间"
      />
    ),
  },
  {
    prop: "endTime",
    title: "结束时间",
    slot: (form) => (
      <el-date-picker
        v-model={form.value.endTime}
        value-format="YYYY-MM-DDTHH:mm:ss"
        type="datetime"
        placeholder="结束时间"
      />
    ),
  },
  {
    prop: "mid",
    title: "地图",
    slot: (form) => (
      <el-select
        onChange={(value) => handleSelectMap(form, value)}
        class="w-full"
        v-model={form.value.mid}
        placeholder="地图"
      >
        {mapList.value.map((item) => (
          <el-option label={item.name} value={item.id}></el-option>
        ))}
      </el-select>
    ),
  },
  {
    prop: "cabinetIds",
    title: "巡检机柜",
    slot: (form) => (
      <el-select
        class="w-full"
        v-model={form.value.cabinetIds}
        placeholder="巡检机柜"
        multiple
        collapse-tags
        onChange={(val) => handleChangeCabinet(val, form)}
      >
        {cabinetList.value.map((item) => (
          <el-option label={item.cabinetName} value={item.id}></el-option>
        ))}
      </el-select>
    ),
  },
  {
    prop: "deviceIds",
    title: "巡检设备",
    slot: (form) => (
      <el-select
        class="w-full"
        v-model={form.value.deviceIds}
        placeholder="巡检设备"
        multiple
        collapse-tags
      >
        {deviceList.value.map((item) => (
          <el-option-group label={item.label}>
            {item.options.map((option) => (
              <el-option
                label={option.deviceName}
                value={option.id}
              ></el-option>
            ))}
          </el-option-group>
        ))}
      </el-select>
    ),
  },
  // {
  //   prop: "route",
  //   title: "路线",
  //   slot: (form) => (
  //     <KonvaEditor
  //       hasAdd={true}
  //       hasDelete={true}
  //       hasClear={true}
  //       v-model:route={form.value.route}
  //       bgImg={form.value.mpath}
  //     ></KonvaEditor>
  //   ),
  // },
];

const mapList = ref([]);
async function getMapList() {
  const res = await fetchMapList({ limit: 99999 });
  mapList.value = res.data.list;
}

getMapList();

function handleSelectMap(form, value) {
  form.value.cabinetIds = [];
  form.value.deviceIds = [];
  cabinetList.value = [];
  deviceList.value = [];
  form.value.mpath = mapList.value.find((item) => item.id === value).path;
  // getDeviceList(value);
  getCabinetList(value);
}

function handleQueryDateTimeChange(value, params) {
  params.value.startTime = value ? value[0] : "";
  params.value.endTime = value ? value[1] : "";
  time.value = value ? value : [];
}

function handleResetQuery() {
  time.value = [];
}

const tableRef = ref(null);

async function handleCopy(row) {
  const data = Object.assign({}, row, { id: null, activeStatus: null });
  await createTask(data);
  tableRef.value.getList();
}

async function handleActive(row) {
  await activeTask(row.id);
  tableRef.value.getList();
}

async function handleControl(row, status) {
  await controlTask({ status, task: row.id });
  ElMessage({ type: "success", message: "已发送" });
}

const deviceList = ref([]);
// async function getDeviceList(mid) {
//   const res = await fetchDeviceList(mid);
//   deviceList.value = res.data;
// }

const cabinetList = ref([]);
async function getCabinetList(mid) {
  const res = await cabinet.queryAll({ limit: 999999 });
  cabinetList.value = res.data.list.filter((item) => item.mid === mid);
}

async function handleChangeCabinet(val, form) {
  if (!val) return;
  const PromiseList = val.map((cid) => deviceProfile.queryByCid(cid));
  const resList = await Promise.all(PromiseList);
  deviceList.value = val.map((cid, index) => ({
    label: cabinetList.value.find((item) => item.id === cid).cabinetName,
    options: resList[index].data,
  }));
  const deviceIds = flatten(
    resList.map((res) => res.data.map((item) => item.id))
  );

  form.value.deviceIds = form.value.deviceIds.filter((id) =>
    deviceIds.includes(id)
  );
}

async function handleOpenForm(form) {
  if (!form.value.id) return;
  await getCabinetList(form.value.mid);
  await handleChangeCabinet(form.value.cabinetIds, form);
}

function handleCloseForm() {
  cabinetList.value = [];
  deviceList.value = [];
}
</script>
